package com.ruoyi.functiontest.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.functiontest.mapper.RoadInterchangeTestMapper;
import com.ruoyi.functiontest.domain.RoadInterchangeTest;
import com.ruoyi.functiontest.service.IRoadInterchangeTestService;
import com.ruoyi.function.domain.RoadInterchange;
import com.ruoyi.function.service.IRoadInterchangeService;

/**
 * 枢纽互通里程实测数据测试Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-25
 */
@Service
public class RoadInterchangeTestServiceImpl implements IRoadInterchangeTestService 
{
    @Autowired
    private RoadInterchangeTestMapper roadInterchangeTestMapper;
    
    @Autowired
    private IRoadInterchangeService roadInterchangeService;

    /**
     * 查询枢纽互通里程实测数据测试
     * 
     * @param id 枢纽互通里程实测数据测试主键
     * @return 枢纽互通里程实测数据测试
     */
    @Override
    public RoadInterchangeTest selectRoadInterchangeTestById(Long id)
    {
        return roadInterchangeTestMapper.selectRoadInterchangeTestById(id);
    }

    /**
     * 查询枢纽互通里程实测数据测试列表
     * 
     * @param roadInterchangeTest 枢纽互通里程实测数据测试
     * @return 枢纽互通里程实测数据测试
     */
    @Override
    public List<RoadInterchangeTest> selectRoadInterchangeTestList(RoadInterchangeTest roadInterchangeTest)
    {
        return roadInterchangeTestMapper.selectRoadInterchangeTestList(roadInterchangeTest);
    }

    /**
     * 新增枢纽互通里程实测数据测试
     * 
     * @param roadInterchangeTest 枢纽互通里程实测数据测试
     * @return 结果
     */
    @Override
    public int insertRoadInterchangeTest(RoadInterchangeTest roadInterchangeTest)
    {
        return roadInterchangeTestMapper.insertRoadInterchangeTest(roadInterchangeTest);
    }

    /**
     * 修改枢纽互通里程实测数据测试
     * 
     * @param roadInterchangeTest 枢纽互通里程实测数据测试
     * @return 结果
     */
    @Override
    public int updateRoadInterchangeTest(RoadInterchangeTest roadInterchangeTest)
    {
        return roadInterchangeTestMapper.updateRoadInterchangeTest(roadInterchangeTest);
    }

    /**
     * 批量删除枢纽互通里程实测数据测试
     * 
     * @param ids 需要删除的枢纽互通里程实测数据测试主键
     * @return 结果
     */
    @Override
    public int deleteRoadInterchangeTestByIds(Long[] ids)
    {
        return roadInterchangeTestMapper.deleteRoadInterchangeTestByIds(ids);
    }

    @Override
    public List<RoadInterchangeTest> selectRoadInterchangeTestListForExport(RoadInterchangeTest roadInterchangeTest)
    {
        return roadInterchangeTestMapper.selectRoadInterchangeTestListForExport(roadInterchangeTest);
    }

    /**
     * 删除枢纽互通里程实测数据测试信息
     * 
     * @param id 枢纽互通里程实测数据测试主键
     * @return 结果
     */
    @Override
    public int deleteRoadInterchangeTestById(Long id)
    {
        return roadInterchangeTestMapper.deleteRoadInterchangeTestById(id);
    }

    /**
     * 是否存在子节点
     * 
     * @param id 节点ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean hasChildById(Long id)
    {
        int result = roadInterchangeTestMapper.hasChildById(id);
        return result > 0;
    }

    /**
     * 批量更新实测单位审核状态（review1字段设置为0）
     * 
     * @return 更新的记录数
     */
    @Override
    public int updateReview1ToZero()
    {
        return roadInterchangeTestMapper.updateReview1ToZero();
    }

    /**
     * 校验所有数据的review1字段是否都为0
     * 
     * @return true 所有review1都为0，false 存在review1不为0的数据
     */
    @Override
    public boolean checkAllReview1IsZero()
    {
        int count = roadInterchangeTestMapper.countReview1NotZero();
        return count == 0;
    }

    /**
     * 根据条件批量更新业主审核状态（review2字段设置为0）
     * 
     * @param roadInterchangeTest 查询条件
     * @return 更新的记录数
     */
    @Override
    public int updateReview2ToZeroByCondition(RoadInterchangeTest roadInterchangeTest)
    {
        return roadInterchangeTestMapper.updateReview2ToZeroByCondition(roadInterchangeTest);
    }

    /**
     * 校验所有数据的review1和review2字段是否都不为空且都为0
     * 
     * @return true 所有review1和review2都不为空且为0，false 存在不符合条件的数据
     */
    @Override
    public boolean checkAllReview1AndReview2AreZero()
    {
        int count = roadInterchangeTestMapper.countReview1OrReview2NotZero();
        return count == 0;
    }

    /**
     * 批量更新中心审核状态（review3字段设置为0）
     * 
     * @return 更新的记录数
     */
    @Override
    public int updateReview3ToZero()
    {
        return roadInterchangeTestMapper.updateReview3ToZero();
    }

    /**
     * 导入枢纽互通里程实测数据测试数据
     * 简化导入逻辑：直接按照Excel原始格式导入，通过id和parentid来确定数据
     * 
     * @param roadInterchangeTestList 枢纽互通里程实测数据测试列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importRoadInterchangeTest(List<RoadInterchangeTest> roadInterchangeTestList, Boolean isUpdateSupport)
    {
        if (roadInterchangeTestList == null || roadInterchangeTestList.isEmpty())
        {
            return "导入数据不能为空！";
        }
        
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        // 简化导入逻辑：直接按照Excel原始格式导入
        for (RoadInterchangeTest data : roadInterchangeTestList)
        {
            try
            {
                // 基本数据验证
                if (data.getRoadName() == null) {
                    data.setRoadName("");
                }
                
                // 通过id和parentid来确定数据
                RoadInterchangeTest existingNode = null;
                
                // 使用新的方法通过id和parentid组合来精确匹配数据
                RoadInterchangeTest query = new RoadInterchangeTest();
                query.setId(data.getId());
                query.setParentId(data.getParentId());
                query.setRoadName(data.getRoadName());
                query.setInterchangeName(data.getInterchangeName());
                
                List<RoadInterchangeTest> existingNodes = roadInterchangeTestMapper.selectRoadInterchangeTestByIdAndParentId(query);
                if (existingNodes != null && !existingNodes.isEmpty()) {
                    existingNode = existingNodes.get(0);
                }
                
                if (existingNode != null) {
                    // 已存在节点，如果支持更新则更新
                    if (isUpdateSupport) {
                        existingNode.setRoadName(data.getRoadName());
                        existingNode.setInterchangeName(data.getInterchangeName());
                        existingNode.setDirection1(data.getDirection1());
                        existingNode.setDirection2(data.getDirection2());
                        existingNode.setRampType(data.getRampType());
                        existingNode.setRampLength(data.getRampLength());
                        existingNode.setRemark(data.getRemark());
                        existingNode.setParentId(data.getParentId());
                        
                        roadInterchangeTestMapper.updateRoadInterchangeTest(existingNode);
                        successNum++;
                    } else {
                        // 不支持更新，跳过此条数据
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + ". 数据已存在，跳过: " + data.getRoadName() + "-" + data.getInterchangeName());
                    }
                } else {
                    // 不存在节点，创建新节点
                    RoadInterchangeTest newNode = new RoadInterchangeTest();
                    newNode.setId(data.getId()); // 使用Excel中的id值
                    newNode.setRoadName(data.getRoadName());
                    newNode.setInterchangeName(data.getInterchangeName());
                    newNode.setDirection1(data.getDirection1());
                    newNode.setDirection2(data.getDirection2());
                    newNode.setRampType(data.getRampType());
                    newNode.setRampLength(data.getRampLength());
                    newNode.setRemark(data.getRemark());
                    newNode.setParentId(data.getParentId());
                    
                    roadInterchangeTestMapper.insertRoadInterchangeTest(newNode);
                    successNum++;
                }
                
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + ". 导入失败：";
                if (data.getRoadName() != null)
                {
                    msg += "路段名称：" + data.getRoadName();
                }
                if (data.getInterchangeName() != null)
                {
                    msg += "，互通名称：" + data.getInterchangeName();
                }
                failureMsg.append(msg + e.getMessage());
            }
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            return failureMsg.toString();
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据已导入到系统。");
            return successMsg.toString();
        }
    }
    
    /**
     * 校验所有数据的review1、review2和review3字段是否都不为空且都为0
     * 
     * @return true 所有review1、review2和review3都不为空且为0，false 存在不符合条件的数据
     */
    @Override
    public boolean checkAllReviewFieldsAreZero()
    {
        int count = roadInterchangeTestMapper.countReview1OrReview2OrReview3NotZero();
        return count == 0;
    }
    
    /**
     * 检查所有数据的review1、review2和review3是否为0，并将数据同步到正式表
     * 
     * @return 同步结果信息
     */
    @Override
    public String syncDataToRoadInterchange()
    {
        try {
            System.out.println("开始同步数据到正式表...");
            
            // 1. 查询所有已通过审核的测试表数据
            RoadInterchangeTest query = new RoadInterchangeTest();
            List<RoadInterchangeTest> testDataList = roadInterchangeTestMapper.selectRoadInterchangeTestList(query);
            
            if (testDataList == null || testDataList.isEmpty()) {
                return "同步失败：测试表中没有数据可同步";
            }
            
            int successNum = 0;
            int failureNum = 0;
            StringBuilder resultMsg = new StringBuilder();
            
            // 2. 遍历测试表数据，同步到正式表
            for (RoadInterchangeTest testData : testDataList) {
                try {
                    // 创建正式表实体对象
                    RoadInterchange formalData = new RoadInterchange();
                    formalData.setId(testData.getId());
                    formalData.setParentId(testData.getParentId());
                    formalData.setRoadName(testData.getRoadName());
                    formalData.setInterchangeName(testData.getInterchangeName());
                    formalData.setDirection1(testData.getDirection1());
                    formalData.setDirection2(testData.getDirection2());
                    formalData.setRampType(testData.getRampType());
                    formalData.setRampLength(testData.getRampLength());
                    formalData.setImage(testData.getImage());
                    formalData.setDeptId(testData.getDeptId());
                    formalData.setRoleId(testData.getRoleId());
                    
                    // 检查正式表中是否已存在相同ID的数据
                    RoadInterchange existingData = roadInterchangeService.selectRoadInterchangeById(testData.getId());
                    
                    if (existingData != null) {
                        // 已存在，更新数据
                        formalData.setId(testData.getId());
                        roadInterchangeService.updateRoadInterchange(formalData);
                    } else {
                        // 不存在，插入新数据
                        roadInterchangeService.insertRoadInterchange(formalData);
                    }
                    
                    successNum++;
                    
                } catch (Exception e) {
                    failureNum++;
                    String errorMsg = "<br/>" + failureNum + ". 同步失败：";
                    if (testData.getRoadName() != null) {
                        errorMsg += "路段名称：" + testData.getRoadName();
                    }
                    if (testData.getInterchangeName() != null) {
                        errorMsg += "，互通名称：" + testData.getInterchangeName();
                    }
                    errorMsg += "，错误：" + e.getMessage();
                    resultMsg.append(errorMsg);
                    System.err.println("同步失败 - ID: " + testData.getId() + ", 错误: " + e.getMessage());
                }
            }
            
            // 3. 构建返回结果
            StringBuilder finalMsg = new StringBuilder();
            if (failureNum > 0) {
                finalMsg.append("数据同步完成，但存在部分失败记录。");
                finalMsg.append("成功同步：" + successNum + " 条，失败：" + failureNum + " 条。");
                finalMsg.append(resultMsg.toString());
            } else {
                finalMsg.append("数据同步成功！共同步 " + successNum + " 条记录到正式表。");
            }
            
            System.out.println("数据同步完成：" + finalMsg.toString());
            return finalMsg.toString();
            
        } catch (Exception e) {
            System.err.println("数据同步过程发生异常：" + e.getMessage());
            return "数据同步失败：" + e.getMessage();
        }
    }
}
